  <!--
    - 云打印交互协议（https://support-cnkuaidi.taobao.com/doc.htm#?docId=107014&docType=1）
    - 菜鸟自定义模板电子面单用户操作（https://cloudprint.cainiao.com/print/login.vm?__output_charset=gbk&targetURL=https%3A%2F%2Fcloudprint.cainiao.com%2Fprint%2Ftemplates.htm）
    - isv动态表格打印项示例（https://support-cnkuaidi.taobao.com/docs/doc.htm?treeId=493&articleId=107812&docType=1）
    - 云打印组件如何支持分页打印（https://support-cnkuaidi.taobao.com/support/hotProblemDetail.htm?spm=a219a.7386653.0.0.111e669aNJG3s9&source=search&id=297651&docType=14）
    - 打印模板设置：http://49.4.71.215/wms_new/systemManage/printTpl
   -->
<template>
  <div>
    <h3 class="ml56">请选择打印机</h3>
    <div class="ml56 container">
      <el-radio-group v-model="defaultPrinter">
        <el-radio v-for="item in printersList" :key="item.name" class="list-item" :label="item.name">{{ item.name }}</el-radio>
      </el-radio-group>
    </div>
    <el-row class="btn-main">
      <el-button :disabled="noCustomTemplate" type="primary" @click="processingData">打印</el-button>
    </el-row>
  </div>
</template>

<script>
// 一联单，汇总拣货单模板 <batch>批次号，<tableList>明细列表{goodsName,specifications,position,count}
import { getPrintTemplate } from '@/api/outStorage'
export default {
  name: 'CustomPrin',
  props: {
    // 要打印的数据
    printData: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 要打印的类型，3:汇总拣货单模板，
    printType: {
      type: Number,
      default: 3
    }
  },
  data() {
    return {
      socket: null,
      defaultPrinter: '', // 默认选中的打印机
      printersList: [], // 所有的打印机
      customTplUrl: '', // 选择的自定义面单模板
      noCustomTemplate: false // 自定义面单模板是否为空
    }
  },
  created() {
    this.initsocket()
    this.getTemplate({ type: 1, code: 'zdy' })
  },
  beforeDestroy() {
    this.socket && this.socket.close()
  },
  methods: {
    // 初始化WebSocket
    initsocket() {
      this.socket = new WebSocket('ws://localhost:13528')
      // 建立连接
      this.socket.onopen = e => {
        console.log('Socket连接成功--->', e)
        this.getPrinters()
      }
      // 接受服务器返回的信息
      this.socket.onmessage = e => {
        console.log('received--->', e.data)
      }
      // 关闭连接
      this.socket.onclose = e => {
        console.warn('socket连接已关闭--->', e)
      }
      // 连接错误
      this.socket.onerror = e => {
        console.error('socket连接发生错误--->', e)
      }
    },
    // 获取打印机列表
    getPrinters() {
      const parms = {
        cmd: 'getPrinters',
        requestID: this.getUUID(8, 10),
        version: '1.0'
      }
      this.socket.send(JSON.stringify(parms))
      this.socket.onmessage = (e) => {
        const data = JSON.parse(e.data)
        this.printersList = data.printers
        this.defaultPrinter = data.defaultPrinter
      }
    },
    // 设置打印机配置
    setPrinterConfig() {
      const parms = {
        cmd: 'setPrinterConfig',
        requestID: this.getUUID(8, 10),
        version: '1.0',
        printer: {
          name: this.defaultPrinter,
          needTopLogo: false,
          needBottomLogo: false,
          // horizontalOffset: 0.5,
          verticalOffset: 0.7,
          forceNoPageMargins: true,
          autoPageSize: true,
          orientation: 0,
          autoOrientation: false,
          paperSize: {
            width: 100,
            height: 180
          }
        }
      }
      this.socket.send(JSON.stringify(parms))
    },
    // 处理要打印的数据
    processingData() {
      this.setPrinterConfig()
      const documents = []
      const printObject = {
        cmd: 'print',
        requestID: new Date().getTime(),
        version: '1.0',
        task: {
          taskID: this.getUUID(8, 10),
          preview: false,
          printer: this.defaultPrinter,
          notifyMode: 'allInOne',
          previewType: 'pdf',
          documents: []
        }
      }
      this.printData.forEach((item, index, arr) => {
        const list = item.pickingItemWithRegisterVOList
        const expressBillData = {
          documentID: this.getUUID(8, 10),
          contents: [
            {
              data: {
                total: 0,
                batch: item.wavePickingCode || '',
                tableList: [],
                orderQuantity: item.orderQuantity || '',
                operatorName: item.operatorName || '',
                shipmentName: item.shipmentName || ''
              },
              templateURL: this.customTplUrl
            }
          ]
        }
        const dataList = []
        for (const itemData of list) {
          const { goodsName, goodsBarCode, locationName = '', distributionQuantity = '' } = itemData
          const item = {
            goodsName,
            goodsBarCode,
            position: locationName,
            count: distributionQuantity
          }
          dataList.push(item)
          expressBillData.contents[0].data.total += distributionQuantity
        }
        expressBillData.contents[0].data.tableList = dataList
        documents.push(expressBillData)
      })
      printObject.task.documents = documents
      this.startPrinting(printObject)
    },
    // 开始打印
    startPrinting(printObject) {
      console.log('即将打印的数据---->', JSON.stringify(printObject))
      this.socket.send(JSON.stringify(printObject))
      this.socket.onmessage = (res) => {
        const printResult = JSON.parse(res.data)
        if (printResult.cmd === 'print' && printResult.status === 'failed') {
          this.$message.error(printResult.msg)
        }
        if (printResult.cmd === 'print' && printResult.status === 'success') {
          this.$message.success('打印任务成功执行完毕')
          this.$emit('finshPrint', res.data)
          this.$eventBus.$emit('printFinish')
        }
        console.log('打印结果---->', res.data)
      }
    },
    // 获取自定义打印模板
    getTemplate(parms) {
      getPrintTemplate(parms).then(res => {
        if (res.status === 0 && res.data.length > 0) {
          const data = res.data.filter(item => Number(item.standardWaybillType) == this.printType)
          if (data.length > 0) {
            this.customTplUrl = data[0].standardTemplateUrl
          } else {
            this.noCustomTemplate = true
            this.$message.error('没有找到符合条件的模板！')
          }
        } else {
          this.noCustomTemplate = true
          this.$message.error('暂无模板，不可打印！')
        }
      })
    },
    // 获取请求的UUID，指定长度和进制，如 getUUID(8, 2)   //"01001010" 8 character (base=2)
    getUUID(len, radix) {
      var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
      var uuid = []; var i
      radix = radix || chars.length
      if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
      } else {
        var r
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
        uuid[14] = '4'
        for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | Math.random() * 16
            uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
          }
        }
      }
      return uuid.join('')
    }
  }
}
</script>
<style scoped>
.mtb10 {
  margin: 20px 0 10px 0;
}
.ml56 {
  margin-left: 56px;
}
.container{
  max-height: 320px;
  overflow: auto;
  margin-top: 18px;
}
.btn-main {
  position: absolute;
  right: 50px;
  bottom: 40px;
}
.list-item {
  display: block;
  margin: 10px 0;
}
.tip {
  font-size: 15px;
  font-weight: bold;
}
</style>
